package xq.gwt.ui.widgets.entity;

import xq.gwt.mvc.model.EntityModel;
import xq.gwt.mvc.model.PropertyChangedEvent;
import xq.gwt.mvc.model.PropertyChangedListener;
import xq.gwt.mvc.model.PropertyModel;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridRecord;


public class EntityRecord extends ListGridRecord implements PropertyChangedListener{
	private EntityModel entity;
	private ListGrid entityGrid;
	
	public EntityRecord(EntityModel entity, ListGrid entityGrid) {
		setEntity(entity);
		setEntityGrid(entityGrid);
	}
	
	public EntityRecord(){
		
	}
	
	public void setEntityGrid(ListGrid entityGrid){
		this.entityGrid = entityGrid;
	}
	
	public void setEntity(EntityModel entity){
		removePropertyChangedListeners();
		this.entity = entity;
		clearRecord();
		if(entity == null)
			return;
		PropertyModel[] props = this.entity.getProperties();			
		if(props != null){
			for (int i = 0; i < props.length; i++) {					
				setAttribute(props[i].getName(), props[i].getText());					
			}
		}
		addPropertyChangedListeners();
	}
	
	private void clearRecord(){
		String[] attributes = getAttributes();
		if(attributes == null)
			return;
		for (int i = 0; i < attributes.length; i++) {
			String val = null;
			setAttribute(attributes[i],val);			
		}
	}
	
	
	public EntityModel getEntity() {
		return entity;
	}

	private void removePropertyChangedListeners(){
		if (this.entity == null)
			return;
		if (entity.getProperties() == null)
			return;
		for (int i = 0; i < entity.getProperties().length; i++) {
			entity.getProperties()[i].removePropertyChangedListener(this);
		}
	}
	
	private void addPropertyChangedListeners(){
		if (this.entity == null)
			return;
		if (entity.getProperties() == null)
			return;
		for (int i = 0; i < entity.getProperties().length; i++) {
			entity.getProperties()[i].addPropertyChangedListener(this);
		}
	}
	
	
	@Override
	public void propertyChanged(PropertyChangedEvent event) {
		PropertyModel changedProperty = (PropertyModel)event.getSource();
		if(changedProperty != null){
			setAttribute(changedProperty.getName(), changedProperty.getText());			
			if(entityGrid != null){
				entityGrid.redraw();
			}
		}			
	}		
}
